package com.lc.command;

import com.lc.protocol.DeviceError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Hashtable;

/**
 * Created by zhyioo on 2017/4/29.
 */

public class CommandRunner implements ICommandDriver, ICommand {
    public static String KEY_MODULE = "Module";
    public static String KEY_COMMAND = "Command";
    public static String KEY_ARGUMENTS = "Arguments";

    protected Hashtable<String, ICommandDriver> _moduleMap = new Hashtable<String, ICommandDriver>();

    public CommandRunner() {}

    public void Select(String name, ICommandDriver handler) {
        _moduleMap.put(name, handler);
    }

    public void Select(String name, Object obj) {
        CommandReflecter reflecter = new CommandReflecter(obj);
        _moduleMap.put(name, reflecter);
    }

    public int Count() {
        return _moduleMap.size();
    }

    public void Clear() {
        _moduleMap.clear();
    }

    public boolean Run(String sModule, String cmd, JSONObject arg, JSONObject rlt) {
        ICommandDriver handler = _moduleMap.get(sModule);
        if (handler == null) {
            CommandActuator.LogErr(rlt, DeviceError.ArgRangeErr, sModule + ":模块不存在");
            return false;
        }
        CommandActuator actuator = new CommandActuator();
        actuator.SetHandler(handler);
        return actuator.OnCall(cmd, arg, rlt);
    }

    @Override
    public boolean Run(JSONObject args, JSONObject rlt) {
        String sMoudle = args.optString(KEY_MODULE, "");
        String sCmd = args.optString(KEY_COMMAND, "");
        String sArg = args.optString(KEY_ARGUMENTS, "");

        JSONObject jsonArg = new JSONObject();
        try {
            jsonArg = new JSONObject(sArg);
        } catch (JSONException e) {

        }
        return Run(sMoudle, sCmd, jsonArg, rlt);
    }

    @Override
    public boolean OnCommand(String cmd, JSONObject arg, JSONObject rlt) {
        String sModule = "";
        String sCmd = cmd;
        if(cmd.contains(".")) {
            int index = cmd.indexOf('.');
            sModule = cmd.substring(0, index);
            sCmd = cmd.substring(index);
        }
        return Run(sModule, sCmd, arg, rlt);
    }
}
